/**
 * 用户状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import { request } from '@/utils/request'
import type { User, LoginForm, RegisterForm } from '@/types'

const TOKEN_KEY = 'access_token'
const REFRESH_TOKEN_KEY = 'refresh_token'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(Cookies.get(TOKEN_KEY) || '')
  const refreshToken = ref<string>(Cookies.get(REFRESH_TOKEN_KEY) || '')
  const userInfo = ref<User | null>(null)
  const permissions = ref<string[]>([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const isAdmin = computed(() => userInfo.value?.role === 'admin')
  const isTeacher = computed(() => userInfo.value?.role === 'teacher')
  const isStudent = computed(() => userInfo.value?.role === 'student')
  const isTeacherOrAdmin = computed(() => isAdmin.value || isTeacher.value)
  const userName = computed(() => {
    if (!userInfo.value) return ''
    return userInfo.value.first_name + userInfo.value.last_name || userInfo.value.username
  })

  // 设置token
  const setToken = (accessToken: string, refreshTokenValue?: string) => {
    token.value = accessToken
    Cookies.set(TOKEN_KEY, accessToken, { expires: 1 }) // 1天过期
    
    if (refreshTokenValue) {
      refreshToken.value = refreshTokenValue
      Cookies.set(REFRESH_TOKEN_KEY, refreshTokenValue, { expires: 7 }) // 7天过期
    }
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
    refreshToken.value = ''
    Cookies.remove(TOKEN_KEY)
    Cookies.remove(REFRESH_TOKEN_KEY)
  }

  // 设置用户信息
  const setUserInfo = (user: User) => {
    userInfo.value = user
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    permissions.value = []
  }

  // 登录
  const login = async (loginForm: LoginForm) => {
    try {
      const response = await request.post('/auth/login/', loginForm)

      // 检查响应结构并提取数据
      let data: any
      if (response && (response as any).data) {
        data = (response as any).data
      } else if (response) {
        data = response
      } else {
        throw new Error('无效的登录响应')
      }

      if (!data.access || !data.refresh || !data.user) {
        throw new Error('登录响应数据不完整')
      }

      setToken(data.access, data.refresh)
      setUserInfo(data.user)

      // 获取用户权限
      await getUserPermissions()

      return data
    } catch (error) {
      clearToken()
      clearUserInfo()
      throw error
    }
  }

  // 注册
  const register = async (registerForm: RegisterForm) => {
    try {
      const response = await request.post('/auth/register/', registerForm)

      // 检查响应结构并提取数据
      let data: any
      if (response && (response as any).data) {
        data = (response as any).data
      } else if (response) {
        data = response
      } else {
        throw new Error('无效的注册响应')
      }

      return data
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (refreshToken.value) {
        await request.post('/auth/logout/', {
          refresh: refreshToken.value
        })
      }
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      clearToken()
      clearUserInfo()
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await request.get('/auth/profile/')

      // 检查响应结构并提取数据
      let data: any
      if (response && (response as any).data) {
        data = (response as any).data
      } else if (response) {
        data = response
      } else {
        throw new Error('无效的用户信息响应')
      }

      setUserInfo(data)
      return data
    } catch (error) {
      clearToken()
      clearUserInfo()
      throw error
    }
  }

  // 获取用户权限
  const getUserPermissions = async () => {
    try {
      const response = await request.get('/auth/permissions/')

      // 检查响应结构并提取数据
      let data: any
      if (response && (response as any).data) {
        data = (response as any).data
      } else if (response) {
        data = response
      } else {
        throw new Error('无效的权限响应')
      }

      permissions.value = data.permissions || []
      return data
    } catch (error) {
      console.error('Get permissions error:', error)
      permissions.value = []
    }
  }

  // 更新用户信息
  const updateUserInfo = async (data: Partial<User>) => {
    try {
      const response = await request.put('/auth/profile/update/', data)

      // 检查响应结构并提取数据
      let responseData: any
      if (response && (response as any).data) {
        responseData = (response as any).data
      } else if (response) {
        responseData = response
      } else {
        throw new Error('无效的更新响应')
      }

      setUserInfo(responseData)
      return responseData
    } catch (error) {
      throw error
    }
  }

  // 修改密码
  const changePassword = async (data: {
    old_password: string
    new_password: string
    confirm_password: string
  }) => {
    try {
      const response = await request.post('/auth/change-password/', data)

      // 检查响应结构并提取数据
      let responseData: any
      if (response && (response as any).data) {
        responseData = (response as any).data
      } else if (response) {
        responseData = response
      } else {
        throw new Error('无效的密码修改响应')
      }

      return responseData
    } catch (error) {
      throw error
    }
  }

  // 刷新token
  const refreshAccessToken = async () => {
    try {
      if (!refreshToken.value) {
        throw new Error('No refresh token')
      }

      const response = await request.post('/auth/token/refresh/', {
        refresh: refreshToken.value
      })

      // 检查响应结构并提取数据
      let data: any
      if (response && (response as any).data) {
        data = (response as any).data
      } else if (response) {
        data = response
      } else {
        throw new Error('无效的token刷新响应')
      }

      setToken(data.access, data.refresh)
      return data.access
    } catch (error) {
      clearToken()
      clearUserInfo()
      throw error
    }
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value) {
      try {
        await getUserInfo()
        await getUserPermissions()
      } catch (error) {
        console.error('Init user info error:', error)
        clearToken()
        clearUserInfo()
      }
    }
  }

  // 检查权限
  const hasPermission = (permission: string): boolean => {
    if (isAdmin.value) return true
    return permissions.value.includes(permission)
  }

  // 检查多个权限（任一满足）
  const hasAnyPermission = (permissionList: string[]): boolean => {
    if (isAdmin.value) return true
    return permissionList.some(permission => permissions.value.includes(permission))
  }

  // 检查多个权限（全部满足）
  const hasAllPermissions = (permissionList: string[]): boolean => {
    if (isAdmin.value) return true
    return permissionList.every(permission => permissions.value.includes(permission))
  }

  return {
    // 状态
    token: readonly(token),
    refreshToken: readonly(refreshToken),
    userInfo: readonly(userInfo),
    permissions: readonly(permissions),
    
    // 计算属性
    isLoggedIn,
    isAdmin,
    isTeacher,
    isStudent,
    isTeacherOrAdmin,
    userName,
    
    // 方法
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    login,
    register,
    logout,
    getUserInfo,
    getUserPermissions,
    updateUserInfo,
    changePassword,
    refreshAccessToken,
    initUserInfo,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions
  }
})
